package com.atguigui.leetcode;

/**
 * 670.最大交换
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/9/13 9:02
 */
public class P670MaximumSwap {
    public static void main(String[] args) {
        Solution solution = new P670MaximumSwap().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int maximumSwap(int num) {
            char[] charArray = String.valueOf(num).toCharArray();
            int n = charArray.length;

            int maxIdx = n - 1;
            int idx1 = -1, idx2 = -1;
            for (int i = maxIdx; i >= 0; i--) {
                //从地位到高位进行依次比较
                if (charArray[i] > charArray[maxIdx]) {
                    maxIdx = i;
                } else if (charArray[i] < charArray[maxIdx]) {
                    idx1 = i;
                    idx2 = maxIdx;
                }
            }
            if (idx1 >= 0) {
                swap(charArray, idx1, idx2);
                return Integer.parseInt(new String(charArray));
            } else {
                return num;
            }

        }

        //交换位子
        private void swap(char[] charArray, int i, int j) {
            char temp = charArray[i];
            charArray[i] = charArray[j];
            charArray[j] = temp;
        }
    }

}
